package com.originskyseed.platform.common.utils;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author tangwh
 * @date 2021-09-30
 * @desc
 **/
public class CsvUtil {
    public static <T> void export(HttpServletRequest request, HttpServletResponse response, String fileName, Map<String, String> header, List<T> list) throws IOException {
        String[] titleStrs = new String[header.size()];
        String[] keys = new String[header.size()];
        Iterator<Map.Entry<String, String>> it = header.entrySet().iterator();
        int i = 0;
        while (it.hasNext()) {
            Map.Entry<String, String> entry = it.next();
            keys[i] = entry.getKey();
            titleStrs[i] = entry.getValue();
            i++;
        }
        if (list == null) {
            list = new ArrayList<>();
        }
        String[][] contents = new String[list.size()][titleStrs.length];
        for (int j = 0; j < list.size(); j++) {
            for (int k = 0; k < titleStrs.length; k++) {
                try {
                    contents[j][k] = getFieldByKey(list.get(j), keys[k]);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        export(request, response, fileName, titleStrs, contents);
    }

    /**
     * 导出excel
     */
    public static void export(HttpServletRequest request, HttpServletResponse response, String fileName, String[] titleStr, String[][] content) throws IOException {
        OutputStreamWriter writer = new OutputStreamWriter(response.getOutputStream(), "GBK");
        BufferedWriter csvWriter = new BufferedWriter(writer, 1024);
        writeRow(new String[]{fileName}, csvWriter);

        response.reset();
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd");

        String fileNameTemp = fileName + sdf1.format(new Date()) + ".csv";
        String formFileName;
        String userAgent = request.getHeader("User-Agent");
        if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
            formFileName = java.net.URLEncoder.encode(fileNameTemp, "UTF-8");
        } else {
            // 非IE浏览器的处理：
            formFileName = new String(fileNameTemp.getBytes("UTF-8"), "ISO-8859-1");
        }

        response.setHeader("Content-Disposition", "attachment;filename=\""
                + formFileName + "\"");
        response.setContentType("multipart/form-data");
        writeRow(titleStr, csvWriter);

        for (String[] strings : content) {
            writeRow(strings, csvWriter);
        }
        csvWriter.close();
        writer.close();
        System.out.println("Excel success");
    }

    public static String getFieldByKey(Object object, String key) throws Exception {
        Object value;
        Field[] fields = object.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            if (field.getName() == null || !field.getName().equals(key)) {
                continue;
            }
            value = field.get(object);
            if (value instanceof Date) {
                return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((Date) value);
            }
            return value == null ? "" : value.toString();
        }
        return "";
    }


    /**
     * 写一行数据方法
     *
     * @param str       数组
     * @param csvWriter BufferedWriter
     * @throws IOException 抛出异常
     */
    private static void writeRow(String[] str, BufferedWriter csvWriter) throws IOException {
        // 写入文件头部
        for (String data : str) {
            if (data == null || "null".equals(data)) {
                csvWriter.write("=\"" + " " + "\",");
            } else {
                csvWriter.write("=\"" + data + "\",");
            }
        }
        csvWriter.newLine();
    }
}


